package com.usian.listener;

import com.rabbitmq.client.Channel;
import com.usian.pojo.DeDuplication;
import com.usian.pojo.LocalMessage;
import com.usian.service.DeDuplicationService;
import com.usian.service.ItemService;
import com.usian.utils.JsonUtils;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ItemMQListener {

    @Autowired
    private ItemService itemService;

    @Autowired
    DeDuplicationService deDuplicationService;

    /**
     * 监听者接收消息三要素：
     *  1、queue
     *  2、exchange
     *  3、routing key
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value="item_queue_order",durable = "true"),
            exchange = @Exchange(value="order_exchange",type= ExchangeTypes.TOPIC),
            key= {"order.*"}
    ))
    public void listen(String msg, Channel channel, Message message) throws Exception {
        //msg： 接收队列中的信息内容
        LocalMessage localMessage = JsonUtils.jsonToPojo(msg, LocalMessage.class);
        //查询本地记录表是否有这条记录
        DeDuplication deDuplication = deDuplicationService.selectDeDuplicationByTxNo(localMessage.getTxNo());
        //进行幂等判断，防止ack应为网络问题没有送达，导致扣减库存业务重复执行
        if (deDuplication == null){
            //本地记录表没有这条记录 说明还没有消费 防止重复消费 重复减掉库存
            System.out.println("接收到消息：" + localMessage.getTxNo());
            Integer result = itemService.updateTbItemByOrderId(localMessage.getOrderNo());
            if(!(result>0)){
                throw new RuntimeException("扣减失败");
            }
            //消费完的信息 添加到本地消息记录表
            deDuplicationService.insertDeDuplication(localMessage.getTxNo());
        }else {
            //如果有这条记录，则不会重复消费
            System.out.println("=======幂等生效：事务"+deDuplication.getTxNo()
                    +" 已成功执行===========");
        }

        //channel：回调机制 message：回调使用的参数
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
}